#!/bin/env python
# coding: utf-8
# author: ZhangTao
# Date  : 2018/1/10
from .InfluxdbHandler import InfluxdbHandler
from util.BasicAuth import BasicAuth
from util.time_transform import unix2str
import json
from urllib.parse import urlencode
import time
import math
from tornado import gen
from util.logConf import log
from util.my_error import InfluxdbError
from influxdb import InfluxDBClient


class MonthCounter(InfluxdbHandler):
    # 执行一次缓存
    @BasicAuth
    @gen.coroutine
    def get(self):
        start_search=time.time()
        clientid = self.get_argument('client', None)
        start_date = self.get_argument('start', None)
        end_date = self.get_argument('end', None)
        message_type = self.get_argument('message_type', None)
        fidis_name = self.get_argument('fidis_name', None)
        interval = self.get_argument('interval', "1")
        unit = self.get_argument('unit', 'm')
        group_by = "{}{}".format(interval, unit)
        str_unix_start, str_unix_end = self.verify_date(start_date, end_date, 0, 1)
        int_unix_start = int(str_unix_start)
        int_unix_end = int(str_unix_end)

        keys = self.get_argument('keys', "*")
        limit = self.get_argument("limit", 50)
        page = self.get_argument('page_index', 1)

        fidis_name, ip = self.get_fidis_ip(fidis_name, clientid)
        influxdb_config = {
            "host": ip,
            "port": "8086"
        }
        url = "http://{}:{}/query?".format(influxdb_config["host"], influxdb_config["port"])
        sql = "select count(payload) from {} where topic !='mosaic' and time >{}s group by time(1d) ".format(clientid, int_unix_start)
        dt = {
            "db": fidis_name,
            "epoch": "s",
            "q": sql
        }
        url_with_encode_params = url + urlencode(dt)
        log.debug(sql)

        try:
            body = yield self.query_influxdb(url_with_encode_params)
        except InfluxdbError as e:
            self.write({"success": False, "error": e.reason})
            return
        # log.debug(body)
        cv = self.get_result_columns_values(body.decode())
        if cv:
            ret = {'success': True, 'column': cv[0], 'values': cv[1]}
        else:
            ret = {'success': True, 'column': ['time', 'count'], 'values': []}
        self.write(ret)
        return
